#include "mysxt.h"
#include "ui_mysxt.h"
#include <QDebug>
#include <QMessageBox>
#include <QFileDialog>

mysxt::mysxt(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::mysxt)
{
    ui->setupUi(this);

    setWindowTitle("摄像头");

  //1. 获取所有相机列表
    m_cameraList = QCameraInfo::availableCameras();
    int camCnt = m_cameraList.count();
    if(camCnt == 0)
    {
      QMessageBox::warning(this,"警告","在本机没有找到相机");
      return;
    }

    for(int i = 0; i<camCnt; i++)
    {
      qDebug()<<"cameraInfo:"<<m_cameraList[i];
      qDebug()<<m_cameraList[i].description();
      ui->cb_camera->addItem(m_cameraList[i].description());
    }

    ui->cb_camera->setCurrentIndex(0); //单个摄像头可省

    m_camera = new QCamera(m_cameraList[0]);

    //2.摄像头取景器,用于显示图像
    m_viewfinder = new QCameraViewfinder(ui->widget);
    m_camera->setViewfinder(m_viewfinder);//将取景器设置给摄像头
    m_viewfinder->resize(640, 480);

    //3.捕获对象
    m_imgCapture = new QCameraImageCapture(m_camera);
    m_imgCapture->setCaptureDestination(QCameraImageCapture::CaptureToFile);

    m_camera->setCaptureMode(QCamera::CaptureStillImage);//摄像头捕获为静态图片

    //4.初始化相机的分辨率
    m_camera->load();//必须加载后,才能获取分辨率
    m_sizeList = m_camera->supportedViewfinderResolutions();
    int sizeCnt = m_sizeList.count();
    for(int i = 0; i < sizeCnt; i++)
    {
      QString wstr = QString::number(m_sizeList[i].width());
      QString hstr = QString::number(m_sizeList[i].height());
      QString str = wstr+"*"+hstr;

      ui->cb_resloution->addItem(str);
    }

  //5.设置摄像头一些参数
    QCameraViewfinderSettings set;
    set.setResolution(m_sizeList[0]);
    m_camera->setViewfinderSettings(set);
}

mysxt::~mysxt()
{
    delete ui;
}

void mysxt::on_bt_open_clicked()
{
    if(m_camera->status() == QCamera::ActiveStatus)
    {
      qDebug()<<"相机已经打开,无需再开";
      return;
    }

    m_viewfinder->show();
    m_camera->start();

    qDebug()<<"相机已打开";
}

void mysxt::on_bt_close_clicked()
{
    if(m_camera->status() != QCamera::ActiveStatus)
    {
      qDebug()<<"相机没有打开,无需关闭";
      return;
    }

    m_viewfinder->hide();
    m_camera->stop();

    qDebug()<<"相机已关闭";
}

void mysxt::on_bt_capture_clicked()
{
    if(m_camera->status() != QCamera::ActiveStatus)
    {
      qDebug()<<"相机没有打开,无法截图";
      return;
    }

    QString filename = QFileDialog::getSaveFileName(this, "保存图像", "./",
                           "img(*.jpg *.png *.ico *.bmp);;all(*.*)");

    m_imgCapture->capture(filename);
}

void mysxt::on_cb_resloution_activated(int index)
{
    //重置摄像头参数
    QCameraViewfinderSettings set;
    set.setResolution(m_sizeList[index]);
    m_camera->setViewfinderSettings(set);
}
